﻿using NB.MGJ.Common.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NB.MGJ.Common;
using NB.MGJ.FrameWork;
using NB.MGJ.Model;
using MySql.Data.MySqlClient;
using L.EntityFramework;

namespace NB.MGJ.Service
{
    public class HomeService : BaseService
    {
        private BaseRepository _baseRepository = new BaseRepository();
        private BaseRepository<L.EntityModel.EntityContext> _baseRepository2;
        public HomeService()
        {
            _baseRepository2 = CreateBaseRepository<L.EntityModel.EntityContext>();
        }
        public string AddTableSizeService()
        {

            //1.模拟得到用户的数据
            List<ObjKeyValueList> okvl = new List<ObjKeyValueList>();
            okvl.Add(AddListTest("文字类型", "员工姓名"));
            okvl.Add(AddListTest("数字类型", "员工年龄"));

            ///2.定义表名 
            /// 根据 客户企业名首字母、管理名称首字母、六位日期 例如：nbbmgl170718（诺标、部门管理、日期）
            string tablesize = GetTableSize("光明牛奶", "人员管理");
            string strsql = "CREATE TABLE " + tablesize + "(";
            int i = 0;
            foreach (var item in okvl)
            {
                i++;
                if (item.Key == "文字类型")
                {
                    item.Key = "nvarchar(500)";
                }
                else if (item.Key == "数字类型")
                {
                    item.Key = "int";
                }
                else if (item.Key == "超长文本")
                {
                    item.Key = "nvarchar(8000)";
                }
                string douhao = "";
                if (i != okvl.Count)
                {
                    douhao = ",";
                }
                strsql += "" + item.Value + "  " + item.Key + douhao;
                //拼接出字段之后
            }
            strsql += ")";

            int count = _baseRepository.ExecuteSql<int>(strsql);
            return "";
        }

        /// <summary>
        ///  定义表名 根据 客户企业名首字母、管理名称首字母、六位日期 例如：nbbmgl170718（诺标、部门管理、日期）
        /// </summary>
        /// <returns></returns>
        public static string GetTableSize(string complate, string manager)
        {
            return CharacterHelper.GetChineseSpell(complate) + "_" + CharacterHelper.GetChineseSpell(manager) + System.DateTime.Now.ToString("yyMMdd");
        }

        /// <summary>
        /// 模拟获取到用户插入的数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public ObjKeyValueList AddListTest(string key, string value)
        {
            ObjKeyValueList ol = new ObjKeyValueList();
            ol.Key = key;
            ol.Value = value;
            return ol;
        }

        #region  小程序登陆
        public L.EntityModel.V_User2 WX_UserLogin(LogOnModel userInfo)
        {
            #region MyRegion
            //            bool _Wx_Logon = false;
            //            string _where = string.Empty;
            //            if (string.IsNullOrWhiteSpace(userInfo.UserName) && string.IsNullOrWhiteSpace(userInfo.Password) && !string.IsNullOrWhiteSpace(userInfo.WxOpenId))
            //            {
            //                _where = string.Format(" `a`.WXID = '{0}' ", userInfo.WxOpenId);
            //                _Wx_Logon = true;
            //            }
            //            else
            //            {
            //                _where = string.Format(" `a`.LoginName = '{0}' ", userInfo.UserName);
            //            }
            //            string sql = string.Format(@"SELECT
            //	                                     `a`.`ID` AS `ID`,
            //	                                     `a`.`ViewDel` AS `ViewDel`,
            //	                                     `a`.`ViewFlag` AS `ViewFlag`,
            //	                                     `a`.`EnterpriseId` AS `EnterpriseId`,
            //	                                     `a`.`RealName` AS `RealName`,
            //	                                     `a`.`LoginName` AS `LoginName`,
            //	                                     `a`.`Pwd` AS `Pwd`,
            //	                                     `a`.`Modile` AS `Modile`,
            //	                                     `a`.`Remark` AS `Remark`,
            //	                                     `a`.`DisableTime` AS `DisableTime`,
            //	                                     `a`.`ChangeLoginID` AS `ChangeLoginID`,
            //	                                     `a`.`ChangeLoginName` AS `ChangeLoginName`,
            //	                                     `a`.`ChangeDate` AS `ChangeDate`,
            //	                                     `a`.`City` AS `City`,
            //	                                     `b`.`EnterpriseName` AS `EnterpriseName`,
            //                                         `b`.`EndTime`,
            //                                         `b`.`Code`,
            //	                                     `a`.`Distributor` AS `Distributor`,
            //	                                     `a`.`Type` AS `Type`,
            //                                         `a`.`WXID`,
            //                                         (SELECT GROUP_CONCAT('Ox',D.Rid) FROM sys_roleuserinfo D WHERE D.Uid = A.ID) roleNames,
            //                                          `b`.HeadId
            //                                       FROM
            //                                       	(
            //                                       		`sys_user` `a`
            //                                       		LEFT JOIN `organization_enterprise` `b` ON (
            //                                       			(
            //                                       				`a`.`EnterpriseId` = `b`.`ID`
            //                                       			)
            //                                       		)
            //                                       	)
            //                                       WHERE
            //		                              `a`.`ViewDel` = 0
            //		                              AND `b`.`ViewFlag` = 1 AND {0}
            //	                                  ", _where);
            //            var UserInfo = _baseRepository2.SearchFirstOrDefault<L.EntityModel.V_User>(sql);
            //            var _info = _baseRepository.ExecuteText<V_User>(sql);
            //            if (_info != null)
            //            {
            //                if (_Wx_Logon)
            //                {
            //                    return _info;
            //                }
            //                if (MD5Manager.Gen_MD5(userInfo.Password, true) == _info.Pwd)
            //                {
            //                    return _info;
            //                }
            //                else
            //                {
            //                    return null;
            //                }
            //            }
            //            else
            //            {
            //                return null;
            //            } 
            #endregion
            bool _Wx_Logon = false;
            string _where = string.Empty;
            if (string.IsNullOrWhiteSpace(userInfo.UserName) && string.IsNullOrWhiteSpace(userInfo.Password) && !string.IsNullOrWhiteSpace(userInfo.WxOpenId))
            {
                _where = string.Format(" `a`.WXID = '{0}' ", userInfo.WxOpenId);
                _Wx_Logon = true;
            }
            else
            {
                _where = string.Format(" `a`.LoginName = '{0}' ", userInfo.UserName);
            }
            string sql = string.Format(@"SELECT
	                                     `a`.`ID` AS `ID`,
	                                     `a`.`EnterpriseId` AS `EnterpriseId`,
	                                     `a`.`RealName` AS `RealName`,
	                                     `a`.`LoginName` AS `LoginName`,
	                                     `a`.`Pwd` AS `Pwd`,
                                         `a`.`UserImg` AS `UserImg`,
	                                     `a`.`Modile` AS `Modile`,
	                                     `a`.`DisableTime` AS `DisableTime`,
	                                     `a`.`ChangeLoginID` AS `ChangeLoginID`,
	                                     `a`.`ChangeLoginName` AS `ChangeLoginName`,
	                                     `a`.`ChangeDate` AS `ChangeDate`,
	                                     `b`.`EnterpriseName` AS `EnterpriseName`,
                                         `b`.`EndTime`,
                                         `b`.`Code`,
	                                     `a`.`Distributor` AS `Distributor`,
	                                     `a`.`Type` AS `Type`,
                                         `a`.`WXID`,
                                         (SELECT GROUP_CONCAT('Ox',D.Rid) FROM sys_roleuserinfo D WHERE D.Uid = A.ID) roleNames,
                                          `b`.HeadId
                                       FROM
                                       	(
                                       		`sys_user` `a`
                                       		LEFT JOIN `organization_enterprise` `b` ON (
                                       			(
                                       				`a`.`EnterpriseId` = `b`.`ID`
                                       			)
                                       		)
                                       	)
                                       WHERE
		                              `a`.`ViewDel` = 0
		                              AND `b`.`ViewFlag` = 1 AND {0}
	                                  ", _where);
            //MySqlParameter[] parametes = new MySqlParameter[]{
            //    new MySqlParameter("@WxOpenId",userInfo.WxOpenId),
            //    new MySqlParameter("@UserName",userInfo.UserName)
            //};
            var UserInfo = _baseRepository2.SearchFirstOrDefault<L.EntityModel.V_User2>(sql);
            if (UserInfo != null)
            {
                if (_Wx_Logon)
                {
                    return UserInfo;
                }
                if (MD5Manager.Gen_MD5(userInfo.Password, true) == UserInfo.Pwd)
                {
                    return UserInfo;
                }
            }
            return null;
        }

        #endregion

        /// <summary>
        /// 密码验证
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="userid"></param>
        /// <returns></returns>
        public bool UserLogin(string username, string password, out int? userid)
        {
            userid = null;
            var UserInfo = _baseRepository2.SearchFirstOrDefault<L.EntityModel.Sys_User>(p => p.LoginName == username);
            if (UserInfo == null)
            {
                return false;
            }
            if (MD5Manager.Gen_MD5(password, true) == UserInfo.Pwd)
            {
                userid = UserInfo.ID;
                return true;
            }
            return false;
            //EncryptHelper _eh = new EncryptHelper();
            //string sql = "select ID,Pwd from Sys_User where LoginName COLLATE utf8_bin=@LoginName";
            //MySqlParameter[] parameters = new MySqlParameter[] 
            //{
            //    new MySqlParameter("@LoginName",username)
            //};
            //var _info = _baseRepository.ExecuteText<Sys_User>(sql, parameters);
            //if (_info != null)
            //{
            //    if (MD5Manager.Gen_MD5(password, true) == _info.Pwd)
            //    {
            //        userid = _info.ID.ToString();
            //        return true;
            //    }
            //    else
            //    {
            //        return false;
            //    }
            //}
            //else
            //{
            //    return false;
            //}
        }

        /// <summary>
        /// 通过用户编号获取用户（主表）信息
        /// </summary>
        /// <param name="userid">用户编号</param>
        /// <returns></returns>
        public L.EntityModel.V_User GetUserByUserId(int userid)
        {
            //int UserId = Convert.ToInt32(userid);
            string sql = string.Format(@"select a.ID,a.EnterpriseId,a.RealName,a.LoginName,a.Modile,a.Province,a.UserImg,
                                              a.City, a.AdminRoleID,b.EnterpriseName,b.Img,b.code,a.Distributor,b.HeadId from Sys_User a  
                                              left join Organization_Enterprise b on a.EnterpriseId=b.ID  
                                              where a.ViewDel=0 and a.ViewFlag=1 and b.ViewFlag=1 and a.ID={0}", userid);
            return _baseRepository2.SearchFirstOrDefault<L.EntityModel.V_User>(sql);
            //通过用户编号获取用户（主表）信息
            //   string sql = "select ButtonId,Pwd,RealName,LoginName from Sys_User  where ButtonId='" + Convert.ToInt32(userid) + "'";
            //   string sql = @"select a.ID,a.EnterpriseId,a.RealName,a.LoginName,a.Modile,a.Province,a.UserImg,
            //                           a.City, a.AdminRoleID,b.EnterpriseName,b.Img,b.code,a.Distributor,b.HeadId from Sys_User a  
            //                           left join Organization_Enterprise b on a.EnterpriseId=b.ID  
            //                           where a.ViewDel=0 and a.ViewFlag=1 and b.ViewFlag=1 and a.ID=@UserID";
            //   MySqlParameter[] parameters = new MySqlParameter[] 
            //   {
            //       new MySqlParameter("@UserID",userid)
            //   };
            //   var _info = _baseRepository.ExecuteText<V_User>(sql, parameters);
            //   if (_info == null) return null;
            //   return _info;
        }

        //public int GetDistributor(string userid)
        //{
        //    string sql = "select Distributor from sys_user where ID=" + userid;
        //    var res = _baseRepository.GetSingle(sql);
        //    int result = Convert.ToInt32(res);
        //    return result;
        //}

        #region 获取当前用户是否有末读消息&设置消息为已读
        public List<L.EntityModel.Sys_PushMessage> GetUserNotReadMessage(int userId, L.EntityModel.Sys_PushMessage pushMessage = null)
        {
            List<L.EntityModel.Sys_PushMessage> Result = new List<L.EntityModel.Sys_PushMessage>();
            //string _insert = string.Empty;
            if (pushMessage != null)
            {
                _baseRepository2.Insert<L.EntityModel.Sys_PushMessage>(pushMessage);
                //_insert = string.Format(
                //      "INSERT INTO sys_pushmessage(`ID`,`PushContent`,`PushDate`,`ReciveUserId`,`IsRead`) VALUES('{0}','{1}','{2}','{3}','{4}');"
                //      , pushMessage.ID, pushMessage.PushContent, pushMessage.PushDate, pushMessage.ReciveUserId, pushMessage.IsRead);
                //_result.Add(pushMessage);
                Result.Add(pushMessage);
            }
            Result.AddRange(_baseRepository2.SearchList<L.EntityModel.Sys_PushMessage>(p => p.ReciveUserId == userId && p.IsRead == 0));
            return Result;
            //string _select = string.Format("{0}SELECT * FROM SYS_PUSHMESSAGE WHERE ReciveUserId = '{1}' AND IsRead = 0 ", _insert, userId);
            //_result.AddRange(_baseRepository.ExecuteSqlCollection<Sys_PushMessage>(_select).ToList());
            //return _result;
        }


        public void SetUserMessageIsRead(string[] messageId)
        {
            string _sql = string.Format("UPDATE SYS_PUSHMESSAGE SET IsRead = 1 WHERE ID IN({0})", string.Join(",", messageId));
            _baseRepository2.Update(_sql);
            //_baseRepository.ExecuteSql<int>(_sql);
        }
        #endregion
    }
}
